//
//  Leaf.swift
//  FrogGame
//
//  Created by wanght on 2016/12/2.
//  Copyright © 2016年 wanght. All rights reserved.
//

import SpriteKit

class Leaf : SKNode {
    
    
    var array = [Int](repeating: 0, count: 320)
    var leafNodeArray = [SKSpriteNode]()
    
    let disForPerStep = 150
    let oneTimeInterval = 0.15
    
    override init() {
        
        super.init()
        
        initArray()
        
        initSpriteNode()
        
    }
    
    func initArray() {
        
        array[0] = 1
        
        for index in 1...319 {
            
            let randomNumber = arc4random() % 8
            
            let change : Int = index / 80
            
            if((change == 0 && index % 7 == 0) || (change == 1 && index % 10 == 0) || ( change == 2 && index % 12 == 0) || (change == 3 && index % 15==0)){
                
                array[index] = 2
                
            } else if(( randomNumber >= 0 && randomNumber <= 3) && array[index - 1] != 0)
            {
                array[index]=0;
                continue
            }else
            {
                array[index]=1;
            }
            
        }
    }
    
    func initSpriteNode() {
    
        //create all some leaf from array
        for index in 0...319 {
            
            let noneNode = SKSpriteNode()
            leafNodeArray.append(noneNode)
            
            if array[index] > 0 {
                
                leafNodeArray[index] = SKSpriteNode(imageNamed: "leaf")
                leafNodeArray[index].size = CGSize(width: 130, height: 60)
                leafNodeArray[index].position.x = CGFloat(667 + 150 * index)
                leafNodeArray[index].position.y = 250
                leafNodeArray[index].zPosition = 1
                addChild(leafNodeArray[index])
                
                if array[index] == 2 {
                    
                    let timeNode = SKSpriteNode(imageNamed: "clock")
                    timeNode.size = CGSize(width: 100, height: 100)
                    timeNode.position.y += 30
                    timeNode.zPosition = 1
                    leafNodeArray[index].addChild(timeNode)
                    
                } 
            }
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func move(stepNumber: Int, currentIndex: Int) {
        
        let moveAction = SKAction.moveBy(x: -CGFloat(stepNumber * disForPerStep), y: 0, duration: oneTimeInterval * 2)

        for index in 0...319 {
            
            if stepNumber < 0 {
                leafNodeArray[index].run(SKAction.sequence([moveAction.reversed(), moveAction]))
            } else {
                leafNodeArray[index].run(moveAction,
                                         completion: {if currentIndex==index{self.leafNodeArray[index].removeAllChildren();}})
            }
        }
    }

}
